package com.kotasoft.iip.integration.predicates.insurance;

import java.util.List;

import javax.inject.Inject;

import org.apache.camel.Exchange;
import org.apache.camel.Predicate;

import com.kotasoft.iip.model.insurance.Contract;
import com.kotasoft.iip.model.insurance.Order;
import com.kotasoft.iip.model.interfaces.HasContract;
import com.kotasoft.iip.model.interfaces.HasOrder;
import com.kotasoft.iip.services.OrderService;

public class ContractHasPendingOrders implements Predicate {

	@Inject
	private OrderService orderService;

	public boolean matches(Exchange exchange) {
		Contract contract = resolveContract(exchange);
		List<Order> orders = orderService.getPendingOrders(contract);
		return !orders.isEmpty();
	}

	private Contract resolveContract(Exchange exchange) {
		if (exchange.getIn().getBody(HasContract.class) != null) {
			return exchange.getIn().getBody(HasContract.class).getContract();
		} else if (exchange.getIn().getBody(HasOrder.class) != null) {
			return exchange.getIn().getBody(HasOrder.class).getOrder().getContract();
		} else {
			throw new RuntimeException("Cant resolve contract in message");
		}
	}
}
